// Coded by Carlos del Ojo Elias (deepbit@gmail.com)


/*
 * Ext JS Library 2.2.1
 * Copyright(c) 2006-2009, Ext JS, LLC.
 * licensing@extjs.com
 * 
 * http://extjs.com/license
 */

//
// This is the main layout definition.
//
//


Ext.onReady(function(){


	///////////////////////////////////// GLOBAL ///////////////////////////////////////////////////////


	Ext.BLANK_IMAGE_URL="images/s.gif";

	var DICTS = new Ext.data.SimpleStore({ url: '/getDiccFiles', fields: ['dicfile'], autoLoad: true });
	var ENCODINGS = new Ext.data.SimpleStore({ url: '/getEncodings', fields: ['encodingname'], autoLoad: true });
	var GLOBAL_SETTINGS_HELP="Here you can define the settings used by any kind of fuzzing (General or Path).<br><br>You can add payloads in the <b>Cookie</b>,<b>Headers</b> and <b>Auth string</b> fields right clicking on the desired place.<br><br>You can also une an external proxy to get anonymous.<br><br>The only required field is <b>Threads</b>.";
	var GENERAL_FUZZ_HELP="In this panel you can add payloads anywhere you want, in the url or in the POST data fields. You can use right click anywhere to add a payload.<br><br>The only required field is <b>Url</b>.<br><br> * Payloads used in Global settings <b>TAKE EFFECT</b> in the fuzz.";
	var PATH_FUZZ_HELP="In this panel you can fuzz a large number of URL's. This type of attack is aimed to perform path discovery attacks. Here you can't use payloads. The payload is automatically added at the end of every url, so you only must ensure to end every url with a slash '/'<br><br>The required fields are <b>Url list</b> and <b>Dictionary</b>.<br><br>Extra file extensions can be specified in comma separated format, eg: php,asp,html,jsp<br><br>Default recursion is 1, so there isn't recursion by default<br><br> * Payloads used in Global settings <b>DON'T TAKE EFFECT</b> in the fuzz.";

	var tb = new Ext.Toolbar();
	tb.render("menuPanel");

	tb.add( new Ext.BoxComponent({autoEl: {tag: 'img', src:'images/webreak-btn.png'}}),
			new Ext.BoxComponent({width: 10, autoEl: {tag: 'div'}}),
			{
				xtype: 'tbbutton',
				menuAlign: 'r',
				cls: 'x-btn-text-icon',
				icon: 'images/info.png',
				text:'About',
				handler: function (){
					Ext.Msg.alert("About","<b>WeBreak 0.1.2 BETA</b> by Carlos del Ojo Elias (deepbit)<br>e-mail: deepbit@gmail.com<br>edge-security.com<br><hr>Tool based on Wfuzz, developed by:<br>Carlos del Ojo and Christian Martorella");}
			},{
				xtype: 'tbbutton',
				menuAlign: 'r',
				cls: 'x-btn-text-icon',
				icon: 'images/logout.png',
				text:'Quit',
				handler: function (){ Ext.Msg.confirm("Quit WeBreak","This operation will close WeBreak loosing all the results, are you sure ? ", function(btn){if (btn=='yes') document.location='/logout'});}
			});


	var mytoolbarPanel = {
		id: 'tb-panel',
		region: 'north', 
		border: false,
		split: false,
		height: 25,
		items: [tb  ]

	};

	function createContextMenu(dic)
	{
		var retobj=Array();
		var textObj=dic.obj;

		if ( dic.encodings==true)
			retobj=retobj.concat(encodingsMenu(textObj));
		if ( dic.payloads==true)
			retobj.push({ text: 'Add payload', icon: 'images/add.png',  TO: textObj, handler: function(){PayGrid.TO=this.TO , PayWin.show(); Ext.example.msg("Add payload","Double click on an item to add a payload",1)} });
			
		return retobj;
	}

	/////////////////////////////////////////////////////////7 MAIN TAB /////////////////////////////////////////////////////////////////////
	/////////////////////////////////////////////////////////7 MAIN TAB /////////////////////////////////////////////////////////////////////
	/////////////////////////////////////////////////////////7 MAIN TAB /////////////////////////////////////////////////////////////////////
	/////////////////////////////////////////////////////////7 MAIN TAB /////////////////////////////////////////////////////////////////////
	//
	//	RECORDS
	//
	var Payload = Ext.data.Record.create([
           {name: 'payid', type: 'string'},
           {name: 'paytype', type: 'string'},
           {name: 'payencoding', type: 'string'},
           {name: 'payval', type: 'string'}    
      ]);

	var globalPayload=0;

	// SETTINGS FORM PANEL

	var settingForm = new Ext.form.FormPanel({
			title: "Global settings",
			collapsible: true,
			collapsed: true,
			hideCollapseTool: true,
			titleCollapse: true,
			frame: true,
			labelWidth: 80,
			defaultType: 'textfield',
	
			items: [
			{ 
					xtype: 'textarea', 
					id: 'cookieTA',
					fieldLabel: 'Cookie',
					width: '100%',
					listeners: { render: function(c){ c.getEl().on({ contextmenu: function(e,c) { e.stopEvent(); var a= new Ext.menu.Menu({ items: createContextMenu({obj: c, encodings: true,payloads: true }) }); var xy = e.getXY(); a.showAt(xy); } }); } }
			},{
					xtype: 'textarea', 
					id: 'headersTA',
					fieldLabel: 'Headers',
					width: '100%',
					listeners: { render: function(c){ c.getEl().on({ contextmenu: function(e,c) { e.stopEvent(); var a= new Ext.menu.Menu({ items: createContextMenu({obj: c, encodings: true,payloads: true }) }); var xy = e.getXY(); a.showAt(xy); } }); } }
			},{
					fieldLabel: 'Proxy',
					id: 'proxyTF',
					width: '20%'  // anchor width by percentage
			},{
					xtype: 'numberfield', 
					fieldLabel: 'Threads',
					value: 10,
					width: '20%',  // anchor width by percentage
					id: 'threadsTF'
			},{ 
					xtype: 'combo', 
					id: 'authtypeTF',
					fieldLabel: 'Authentication Type', 
					editable: false,
					mode: 'local', 
					triggerAction: 'all',
					tabIndex: 0, 
					value: 'None',
					store: new Ext.data.SimpleStore({ fields: ['authtype'], data : [['None'],['Basic'],['Digest'],['Ntlm']]}), 
					displayField:'authtype', 
					width: '20%' 
			},{
					fieldLabel: 'Auth string',
					id: 'authTF',
					width: '20%',  // anchor width by percentage
					listeners: { render: function(c){ c.getEl().on({ contextmenu: function(e,c) { e.stopEvent(); var a= new Ext.menu.Menu({ items: createContextMenu({obj: c, encodings: true,payloads: true }) }); var xy = e.getXY(); a.showAt(xy); } }); } }
			}],
			listeners: {  beforeexpand: function(a,b){ GeneralFuzzing.collapse(); PathFuzzing.collapse();  }  },
			buttons: [{
				text: "Help",
				cls: 'x-btn-text-icon',
				icon: "images/help.png",
				handler: function(){
					Ext.Msg.alert("Global settings help",GLOBAL_SETTINGS_HELP)
			}}]
		});


	
	var GeneralFuzzing = new Ext.form.FormPanel({
		title: "General Fuzzing: Fuzz on any request place",
		collapsible: true,
		hideCollapseTool: true,
		titleCollapse: true,
		collapsed: true,
		frame: true,
		labelWidth: 75,
		defaultType: 'textfield',
		items:[{
			/////////////////// URL		
			id: 'urlTF',
			fieldLabel: 'Url',
			width: '100%',
			listeners: { render: function(c){ c.getEl().on({ contextmenu: function(e,c) { e.stopEvent(); a= new Ext.menu.Menu({ items: createContextMenu({obj: c, encodings: true,payloads: true }) }); var xy = e.getXY(); a.showAt(xy); } }); } }
		},{
			/////////////////// POST DATA
			id: 'postTA',
			xtype: 'textarea',
			fieldLabel: 'Post data',
			width: '100%',
		//	height: 70,
			listeners: { render: function(c){ c.getEl().on({ contextmenu: function(e,c) { e.stopEvent(); a= new Ext.menu.Menu({ items: createContextMenu({obj: c, encodings: true,payloads: true }) }); var xy = e.getXY(); a.showAt(xy); } }); } }
		}
		],
		buttons: [{
			cls: 'x-btn-text-icon',
			icon: 'images/settings2.png',
			text: 'Launch',
			handler: function(){
				var cookie=b64encode(settingForm.findById('cookieTA').getValue());
				var headers=b64encode(settingForm.findById('headersTA').getValue());
				var proxy=b64encode(settingForm.findById('proxyTF').getValue());
				var threads=b64encode(String(settingForm.findById('threadsTF').getValue()));
				var authtype=b64encode(settingForm.findById('authtypeTF').getValue());
				var auth=b64encode(settingForm.findById('authTF').getValue());

				var url=b64encode(GeneralFuzzing.findById('urlTF').getValue());
				var post=b64encode(GeneralFuzzing.findById('postTA').getValue());

				var paylds = new Array();
 
				var st=PayGrid.getStore();

				for (var i=0; i< st.getCount();i++)
				{
					var r=st.getAt(i)
					var str=r.get('payid')+","+r.get('paytype')+","+r.get('payval')+","+r.get('payencoding');
					paylds.push(str);
				}

				paylds=b64encode(paylds.join("|"))

				var fm= new Ext.form.BasicForm(Ext.get('gfform'),{
					id: 'gfform',
					baseParams: {ck: cookie, headers: headers , proxy: proxy, threads: threads, authtype: authtype, auth: auth , url: url, post: post, payloads: paylds},
					method: 'GET',
					reader: Ext.data.JsonReader(),
					url: 'launchFuzz'
				});

				fm.submit({
					success: function(fm,act){ if (act.result){Ext.example.msg("Success",act.result.msg,1)}  } ,
					failure: function(fm,act){ if (act.result){Ext.example.msg("Error",act.result.msg,3) } else { Ext.example.msg("Error",'Unknown Error. Try to launch again.',3)   } } 
				});
			}
		},{
				text: "Help",
				cls: 'x-btn-text-icon',
				icon: "images/help.png",
				handler: function(){ Ext.Msg.alert("General fuzzing help",GENERAL_FUZZ_HELP)}
		}],
		listeners: {  beforeexpand: function(a,b){ PathFuzzing.collapse(); settingForm.collapse();  }  }
	});

	var PathFuzzing = new Ext.form.FormPanel({
		title: "Path Fuzzing: Fuzz on multiple paths",
		collapsible: true,
		hideCollapseTool: true,
		titleCollapse: true,
		collapsed: false,
		frame: true,	
		items: [{
			xtype: 'textarea',
			id: 'UrlPool', 
			fieldLabel: 'Url list',
			width: '100%',
			height: 120,
			listeners: { render: function(c){ c.getEl().on({ contextmenu: function(e,c) { e.stopEvent(); var a= new Ext.menu.Menu({ items: createContextMenu({obj: c, encodings: true }) }); var xy = e.getXY(); a.showAt(xy); } }); } }
		},{
			xtype: 'numberfield', 
			fieldLabel: 'Recursion level',
			id: 'recursion',
			value: 1,
			width: '20%'  // anchor width by percentage
		},{
			xtype: 'textfield',
			fieldLabel: 'Extensions',
			id: 'extensions',
			width: '20%'  // anchor width by percentage
		},{
			xtype: 'combo',
			lazyInit: false,
			id: 'pathDiccPay',
			fieldLabel: 'Dictionary', 
			editable: false,
			mode: 'local', 
			triggerAction: 'all',
			allowBlank: false,
			tabIndex: 0, 
			store: DICTS,
			displayField:'dicfile', 
			validator: function(a) { if (!this.value.length){return false} return true; },
			width: 300
		}],
		buttons: [{
			cls: 'x-btn-text-icon',
			icon: 'images/settings2.png',
			text: 'Launch',
			handler: function (){
				var cookie=b64encode(settingForm.findById('cookieTA').getValue());
				var headers=b64encode(settingForm.findById('headersTA').getValue());
				var proxy=b64encode(settingForm.findById('proxyTF').getValue());
				var threads=b64encode(String(settingForm.findById('threadsTF').getValue()));
				var authtype=b64encode(settingForm.findById('authtypeTF').getValue());
				var auth=b64encode(settingForm.findById('authTF').getValue());
				var dic=b64encode(PathFuzzing.findById('pathDiccPay').getValue());
				var urlpool=b64encode(PathFuzzing.findById('UrlPool').getValue());
				var recursion=b64encode(String(PathFuzzing.findById('recursion').getValue()));
				var exts=b64encode(PathFuzzing.findById('extensions').getValue());
				Ext.Ajax.request({
					url: 'launchFuzz2',
					params: { ck:cookie,headers:headers,proxy:proxy,threads:threads,authtype:authtype,auth:auth,urls:urlpool,recursion:recursion,extensions:exts,dic:dic },
					success: function(act,op){ var msg=Ext.util.JSON.decode(act.responseText).msg; Ext.example.msg("Success",msg,4)},
					failure: function(act,op){ var msg=Ext.util.JSON.decode(act.responseText).msg; Ext.example.msg("Error",msg,4)}
				});
			}

		},{
				text: "Help",
				cls: 'x-btn-text-icon',
				icon: "images/help.png",
				handler: function(){ Ext.Msg.alert("Path fuzzing help",PATH_FUZZ_HELP)}
		}],
		listeners: {  beforeexpand: function(a,b){ GeneralFuzzing.collapse(); settingForm.collapse();  }  }
	});

	////////////////////////// GRIDs ////////////////////////////////////////////////////////////////////////////////////////////////


    // create the data store
    var store = new Ext.data.SimpleStore({
        fields: [ {name: 'payid'}, {name: 'paytype'}, {name: 'payencoding'}, {name: 'payval'} ]
    });

    // create the Grid
    var PayGrid = new Ext.grid.GridPanel({
        store: store,
        columns: [
            {id:'payid',header: "Payload ID", width: 100, sortable: false, dataIndex: 'payid'},
            {header: "Payload type", width: 75, sortable: false,  dataIndex: 'paytype'},
            {header: "Encoding", width: 130, sortable: false,dataIndex: 'payencoding'},
            {header: "Value", width: 160, sortable: false,dataIndex: 'payval'}
        ],
		sm: new Ext.grid.RowSelectionModel({singleSelect:true}),
        stripeRows: true,
        autoExpandColumn: 'payid',
        height:350,
        width:600,
        title:'Payload list',
		renderTo: 'paygrid',
		listeners: { rowdblclick: function (gr,row,e){
			var obj=PayGrid.TO;

			var sel=new Selection(obj);
			sel=sel.create();

			var len=obj.value.length;
			var start=sel.start;
			var end=sel.end;
			var size=len-end;
			var res=gr.getStore().getAt(row).get("payid");

			PayWin.hide();


			obj.value=obj.value.substr(0,start)+res+obj.value.substr(end,size);

		}}
    });

	
	/////////////////////////////////////////////////// PAYLOADS EDITOR ////////////////////////////////////////////////////////////

	var NewPayWin= new Ext.Window({ 
	title: 'New payload', 
    closeAction :'hide',
	width: 400,
	resizable: false,
    items:[ NewPayForm = new Ext.form.FormPanel(
  	{
  		frame: true,
  		items: [{
			/////////////////// COMBO PAYTYPE
  			xtype: 'combo',
  			name: 'paytype', 
			id: 'paytypefld',
  			fieldLabel: 'Paylod Type', 
			editable: false,
			mode: 'local', 
  			triggerAction: 'all',
			tabIndex: 0, 
  			value: 'Range',
  			store: new Ext.data.SimpleStore({ fields: ['paytype'], data : [['Range'],['HexRange'],['File']]}), 
  			displayField:'paytype',
			width: 180,
			listeners:  {select: function(c,r,i){ 
					NewPayForm.remove(NewPayForm.findById('PayloadValue'))
					switch (c.value)
					{
						case 'Range':
							Ext.example.msg('Range selected','Value example: 1-50',3);
							NewPayForm.add({
								xtype: 'textfield', 
								id: 'PayloadValue',
								fieldLabel: 'Range',
								name: 'range',
								allowBlank: false,
								validator: function(a) { var a=a.split('-'); if (a.length!=2 || a[0]>=a[1]) {return false;} return true; },
								width: 120
							});
							break;
						case 'HexRange':
							Ext.example.msg('HexRange selected','Value example: 1f-5c',3);
							NewPayForm.add({
								xtype: 'textfield', 
								id: 'PayloadValue',
								fieldLabel: 'Hex Range',
								name: 'hexrange',
								allowBlank: false,
								validator: function(a) { var a=a.split('-'); if (a.length!=2 || parseInt("0x"+a[0])>=parseInt("0x"+a[1])) {return false;} return true; },
								width: 120 
							});
							break;
						case 'File':
							NewPayForm.add({
								xtype: 'combo',
								id: 'PayloadValue',
								name: 'encoding', 
								fieldLabel: 'File', 
								editable: false,
								mode: 'local', 
								triggerAction: 'all',
								allowBlank: false,
								tabIndex: 0, 
								store: DICTS,
								displayField:'dicfile', 
								validator: function(a) { if (!this.value.length){return false} return true; },
								width: 220
							});
							break;
					}
					NewPayForm.doLayout();
				}
			}
  		},{
				xtype: 'combo',
				id: 'encfld',
				name: 'encoding', 
				fieldLabel: 'Encoding', 
				editable: false,
				mode: 'local', 
				triggerAction: 'all',
				tabIndex: 0, 
				value: 'None',
				store: ENCODINGS,
				displayField:'encodingname', 
				width: 180
		},{
				xtype: 'textfield', 
				id: 'PayloadValue',
				fieldLabel: 'Range',
				name: 'range',
				invalidText: 'asd',
				allowBlank: false,
				validator: function(a) { var a=a.split('-'); if (a.length!=2 || a[0]>=a[1]) {return false;} return true; },
				width: 120  
		}],
		buttons:[{
			text: "Add",
			handler: function(){
				var v1=NewPayForm.findById('paytypefld').value;
				var v2=NewPayForm.findById('encfld').value;
				var a=NewPayForm.findById('PayloadValue');
				if (!a.validate())
					return;
				globalPayload++;
				var v0='{@'+globalPayload+'@}';
				store.add(new Payload({payid: v0, paytype: v1, payencoding: v2, payval: a.getValue()}));
				NewPayWin.hide();
			}
		}]

	})
	]});

	var PayWin = new Ext.Window({
		title: 'Payload manager',
        layout: 'anchor',
        width: 500,
        height: 300,
		modal: true,
        closeAction :'hide',
        plain: true,
		frame: true,
        items: [  PayGrid ],
        buttons: [{
            text: 'New payload',
			handler: function (){
					NewPayWin.show()
				}
		},{
			text: 'Delete payload',
			handler: function (){
				var row=PayGrid.getSelectionModel().getSelected()
				PayGrid.getStore().remove(row);
			}
        }]
    });

	/////////////////////////////////////////////////////// RESULTS TAB ////////////////////////////////////////////////////////////////////
	/////////////////////////////////////////////////////// RESULTS TAB ////////////////////////////////////////////////////////////////////
	/////////////////////////////////////////////////////// RESULTS TAB ////////////////////////////////////////////////////////////////////
	//
	//	RECORDS

	
	var StatusRecord = Ext.data.Record.create([
           {name: 'id', type: 'string'},
           {name: 'state', type: 'string'},
           {name: 'percent', type: 'int'},
           {name: 'count', type: 'string'},
           {name: 'eta', type: 'string'},
           {name: 'url', type: 'string'}    
      ]);

	var ResultsRecord = Ext.data.Record.create([
           {name: 'id', type: 'string'},
           {name: 'code', type: 'string'},
           {name: 'lines', type: 'string'},
           {name: 'words', type: 'string'},
           {name: 'bytes', type: 'string'},
           {name: 'payinfo', type: 'string'}
	]);


	// READERS for grids

	var statusReader = new Ext.data.ArrayReader({}, [
			{name: 'id'},
			{name: 'state'},
			{name: 'percent'},
			{name: 'count'},
			{name: 'eta'},
			{name: 'url'}   
	]);

	var resultsReader = new Ext.data.ArrayReader({}, [
			{name: 'id'},
			{name: 'code'},
			{name: 'lines'},
			{name: 'words'},
			{name: 'bytes'},
			{name: 'payload'}
	]);
	

	//////////////////////////////////////////////////////////////// GRIDS /////////////////////////////////////////////////////////////////////

	var StatusSelectionModel = new Ext.grid.ProgressBarSelectionModel({header: "Completed", text:'%', dataIndex:'percent', singleSelect:true});

	var StatusGrid = new Ext.grid.GridPanel({
		region: 'north',
		split: true,
		collapsible: true,
		height: 200,
        stripeRows: true,
		margins: '15 15 3 15',
		autoExpandColumn: 'activity',
		store: new Ext.data.Store({ reader: statusReader }),
		cm: new Ext.grid.ColumnModel([
				{id:'activity',header: "Url", width: 300, sortable: true, dataIndex: 'url'},
				{header: "State", width: 70, sortable: true, dataIndex: 'state'},
				StatusSelectionModel,
				{header: "Request count", width: 80, sortable: false, dataIndex: 'count'},
				{header: "ETA", width: 60, sortable: false, dataIndex: 'eta'}
			]),
		sm: StatusSelectionModel,
		frame:true,
		title:'Fuzz status',
		listeners: { rowclick: function (g,nr,e){
						Ext.TaskMgr.stop(allUpdate)
						var st=g.getStore();
						var row=st.getAt(nr);
						var id=row.get('id');
						Ext.Ajax.request({
							url: 'selectFuzz',
							params: { nfuzz: id },
							success: function(act,op){ 
								var msg=Ext.util.JSON.decode(act.responseText).msg; 
								ResultsGrid.getStore().removeAll();
								updateResultsGrid(msg);
								Ext.TaskMgr.start(allUpdate)
							},
							failure: function(fm,act){ Ext.TaskMgr.start(allUpdate) }
						})
					 	},
						
					 rowcontextmenu: function(g,nr,e) {	
						 e.stopEvent();
						 var row=g.getStore().getAt(nr);
						 var id=row.get("id")
						 var a= new Ext.menu.Menu({ items:[{
							 							text: "Stop",
														icon: "images/cancel.png",
														handler: function(){
															Ext.Ajax.request({              
																url: 'CancelFuzz',               
																params: {id:id},
																success: function(){},
																failure: function(){}
															})
															row.set("state","Stopping")
														}
													},{
														text: "Delete",
														icon: 'images/delete.png',
														handler: function(){
															Ext.Ajax.request({              
																url: 'DeleteFuzz',               
																params: {id:id},
																success: function(){},
																failure: function(){}
															});
															row.set("state","Deleting");
														}
						 						  }]}); 
						 var xy = e.getXY(); 
						 a.showAt(xy);

					 }
		}
	});


	var ResultsGrid = new Ext.grid.GridPanel({
		region: 'center',
		margins: '3 15 15 15',
		store: new Ext.data.Store({ 
			reader: resultsReader ,
			sortInfo: { field: "code", direction: "ASC" }
			}),
		cm: new Ext.grid.ColumnModel([
				{header: "code", width: 60, sortable: true, dataIndex: 'code'},
				{header: "lines", width: 60, sortable: true, dataIndex: 'lines'},
				{header: "words", width: 60, sortable: true, dataIndex: 'words'},
				{header: "bytes", width: 60, sortable: true, dataIndex: 'bytes'},
				{id: "payinfo", header: "payload", width: 120, sortable: true, dataIndex: 'payinfo'}
			]),
		autoExpandColumn: 'payinfo',
		frame:true,
		title:'Fuzz results',
		listeners: {rowclick: function (g,nr,e){
			var row=g.getStore().getAt(nr);
			MyWindow = open("","MyWindow","width=400,height=400");
			
			try
			{ MyWindow.document.location="/getResult?nres="+row.get("id"); 
				}
			catch (err)
			{
				var MyWindow = open("","MyWindow","width=400,height=400");
				MyWindow.close();
				var row=g.getStore().getAt(nr);
				MyWindow = open("","MyWindow","width=400,height=400");
				MyWindow.document.location="/getResult?nres="+row.get("id");
				window.focus();
			}


		//	Ext.Ajax.request({              
		//		url: 'getResult',               
		//		params: {nres:row.get("id")},
		//		success: function(act,op){ 
		//			//var msg=Ext.util.JSON.decode(act.responseText).msg; 
		//			MyWindow = open("","MyWindow","width=400,height=400");
		//			MyWindow.document.location="/getResult?nres="+row.get("id");
		//		//	var doc=MyWindow.document;
		//		//	doc.open();
		//		//	doc.write(act.responseText);
		//		//	doc.close();
		//		}})
		}}
	});


	ResultsGrid.getView().getRowClass = function(record, index){
		     	cd=parseInt(record.get("code"))
				if (cd>=200 && cd < 300)
					return 'green-row';
				else if (cd>=300 && cd<400)
					return 'blue-row';
				else if (cd>=400 && cd<500)
					return 'red-row';
				else if (cd>=500) 
					return 'lila-row';

			      }; 

	///////////////////////////////////////////////////// LAYOUT ///////////////////////////////////////////////////////
	///////////////////////////////////////////////////// LAYOUT ///////////////////////////////////////////////////////
	///////////////////////////////////////////////////// LAYOUT ///////////////////////////////////////////////////////


	var tabs = {
		xtype: 'tabpanel',
		id: 'card-tabs-panel',
		//plain: true,  //remove the header border
		region: 'center',
		margins: '2 5 5 5',
		frame: true,
		activeItem: 0,
		defaults: {bodyStyle: 'padding:15px'},
		items:[{
			layout: 'anchor',
			title: 'Fuzzing',
			frame: true,
			items: [ settingForm, {height: 20, items: []} ,GeneralFuzzing,{height: 20, items: []} ,PathFuzzing ]
		},{
			title: 'Results',
			layout: 'border',
			frame: true,
			items: [ StatusGrid, ResultsGrid ]
		}]
	};

	new Ext.Viewport({
		layout: 'border',
		title: 'WeBreak',
		items: [ {
			layout: 'border',
			frame: true,
			region: 'center',
			items:[ mytoolbarPanel,tabs]
			}
		],
		renderTo: Ext.getBody()
	});

	var el=Ext.get('banner');
	el.setWidth(697);
	el.setHeight(154);
	el.show();
	el.center();
	el.hide();
	el.fadeIn({ endOpacity: 1, easing: 'easeOut', duration: 3});
	el.fadeOut({ endOpacity: 0, easing: 'easeOut', duration: .5, remove: true, useDisplay: false });


////////////////////////////////// TIMERS /////////////////////////////////////////
////////////////////////////////// TIMERS /////////////////////////////////////////
////////////////////////////////// TIMERS /////////////////////////////////////////

	var updateResultsGrid = function (msg){
		var st=ResultsGrid.getStore();
		if (msg.action=="update")
			ResultsGrid.getStore().removeAll();

		for (var i in msg.values)	
		{
			var row=msg.values[i];
			if (typeof row=="object")
			{
				st.addSorted(new ResultsRecord({id: row[0], code: row[1], lines: row[2], words: row[3] , bytes: row[4],payinfo: HtmlDecode(row[5])}));
			}
		}
	}

	var updateStatusGrid = function (msg){
		var st = StatusGrid.getStore();

		var newids=new Object();

		for (var i in msg)
			if (typeof msg[i]=="object")
			{
				newids[parseInt(msg[i][0])]=msg[i];
			}


		var idsActual= new Object();

		for (var i=0; i< st.getCount();i++)
		{
			var r=st.getAt(i)
			var str=r.get('id');
			idsActual[parseInt(str)]=r;
		}

		for (var i in idsActual)
		{
			if (i in newids==false)
			{
				st.remove(idsActual[i]);
				if (!StatusGrid.getSelectionModel().getSelected())
					ResultsGrid.getStore().removeAll();

			}
		}

		for (var i in newids)
		{
			if (i in idsActual==false)
				{st.add(new StatusRecord({id: newids[i][0], state: newids[i][1], percent: newids[i][2], count: newids[i][3] , eta: newids[i][4],url: newids[i][5]}));}
			else
				{
					idsActual[i].set("state",newids[i][1]);
					idsActual[i].set("percent",newids[i][2]);
					idsActual[i].set("count",newids[i][3]);
					idsActual[i].set("eta",newids[i][4]);
				}
		}
			

	}

	var allUpdate = {
		    run: function(){
						Ext.Ajax.request({
						url: 'getStatus',
						success: function(act,op){ 
							var msg=Ext.util.JSON.decode(act.responseText).msg; 
							if ("status" in msg)
								updateStatusGrid(msg.status);
							if ("results" in msg)
								updateResultsGrid(msg.results);
							if ("info" in msg)
							{
								for (var i in msg.info)
								{
									j=msg.info[i];
									Ext.example.msg("Information",j[0],j[1]);
								}
							}
							},
						failure: function(fm,act){}
					})

			    },
		    interval: 3000 //3 second
	};

	Ext.TaskMgr.start(allUpdate);


});
